package registration.adventurezone.thevine.com;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import registration.adventurezone.thevine.com.Constants.ChildrenFilter;


import android.R.integer;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ViewFlipper;

public class CheckOutActivity extends Activity{

    private ListView childrenListView;
    private Button outButton;
    EditText filterBox;
    private ArrayList<ChildViewHolder> childrenList;
    private ChildViewHolder[] childViews;
    private ArrayAdapter<ChildViewHolder> listAdapter;
    private NodeList idList, checkedInList, guardiansList;
    private Document doc;
    private File childrenDatabaseFile;
    private View childListLayout, guardiansLayout;
    private EditText guardiansField;
    private DBChild selectedChild;
    private ImageView imageView;
    private Gallery ga;
    private TextView guardianLabel;
    private ViewFlipper flipper;
    private Animation animInRight, animOutLeft, animOutRight, animInLeft;



	@Override
    public void onCreate( Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checkout_layout);

        loadResourcesById();
        childrenListView = (ListView) findViewById(R.id.childrenList);


    	ArrayList<DBChild> children = XMLResourceHandler.getInstance().getChildrenByStatus(ChildrenFilter.CHECKED_IN);
    	childViews = new ChildViewHolder[children.size()];
    	for (int i=0;i<children.size();i++) {
    		childViews[i] = new ChildViewHolder(children.get(i));
    	}
    	
    	childrenList = new ArrayList<ChildViewHolder>();
        childrenList.addAll(Arrays.asList(childViews));
        listAdapter = new ChildArrayAdapter(this, childrenList, R.layout.simple_list_row);
        childrenListView.setAdapter(listAdapter);
        

        filterBox = (EditText) findViewById(R.id.childrenFilter);


        // By using setTextFilterEnabled method in listview we can filter the listview items.

        childrenListView.setTextFilterEnabled(true);
        
        filterBox.addTextChangedListener(new TextWatcher()
        {


            @Override
            public void onTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
            {
                // TODO Auto-generated method stub

            }



            @Override
            public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3)
            {
                // TODO Auto-generated method stub

            }



            @Override
            public void afterTextChanged( Editable arg0)
            {
                CheckOutActivity.this.listAdapter.getFilter().filter(arg0);
            }
        });
        
        childrenListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			    //view.setSelected(true);
				selectedChild = listAdapter.getItem(position).getDBChild();


				ArrayList<String> guardiansList = new ArrayList<String>();
				for(Guardian g:selectedChild.getGuardians()) {
					guardiansList.add(g.getFirst() + " " + g.getLast());
				}
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	            imm.hideSoftInputFromWindow(filterBox.getApplicationWindowToken(), 0);
	            
				flipper.setInAnimation(animInRight);
			    flipper.setOutAnimation(animOutLeft);
			    flipper.showNext();  
			    
			    ga = (Gallery)findViewById(R.id.Gallery01);
		        ga.setAdapter(new ImageAdapter(getBaseContext(), guardiansList));
		        guardianLabel.setText((String)ga.getAdapter().getItem(0));
		        
		        outButton = (Button) findViewById(R.id.outButton);
		        outButton.setOnClickListener(new OnClickListener() {           
		        	public void onClick(View v) {
		        		
		        		ArrayList<DBChild> toCheckOut = new ArrayList<DBChild>();
		        		toCheckOut.add(selectedChild);
		        		XMLResourceHandler.getInstance().checkOutSelectedChildren(toCheckOut);
		        		
						XMLResourceHandler.getInstance().writeXMLToMem(XMLResourceHandler.getInstance().writeDocToXMLString());
		        		Intent myIntent = new Intent(CheckOutActivity.this, AZregActivity.class);
		        		CheckOutActivity.this.startActivity(myIntent);
		        	}
				});
		        
		        imageView = (ImageView)findViewById(R.id.ImageView01);
		        imageView.setImageResource(R.drawable.prof_pic);

		        ga.setOnItemSelectedListener(new OnItemSelectedListener() {
		
		            @Override
		            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		            	guardianLabel.setText((String)ga.getAdapter().getItem(pos));
						imageView.setImageResource(R.drawable.prof_pic);
		            }
		
		            @Override
		            public void onNothingSelected(AdapterView<?> arg0) {
		
		            }
		
		        });
			}
		});
        
        
		
        
    }
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event){
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	// Are we on the second layout view?
	    	if(flipper.getDisplayedChild() == 1){
	    		// go back to first view
		    	flipper.setInAnimation(animInLeft);
			    flipper.setOutAnimation(animOutRight);
			    flipper.showPrevious(); 
			    return true;
	    	}
	    	// We must be on the first layout view.
	    	else{
	    		//step out of current activity
	    		onBackPressed();
	    		
	    	}
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
    public Document getDomElement(File xmlFile){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
 
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(xmlFile); 
 
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
                // return DOM
            return doc;
    }
    private void loadResourcesById() {
    	guardianLabel = (TextView) findViewById(R.id.guardianLabel);
    	childListLayout = (View) findViewById(R.id.childListLayout);
    	guardiansLayout = (View) findViewById(R.id.guardiansLayout);
    	flipper = (ViewFlipper) findViewById(R.id.flipper);
    	animInRight = AnimationUtils.loadAnimation(this, R.anim.view_trans_in_right);
    	animOutLeft = AnimationUtils.loadAnimation(this, R.anim.view_trans_out_left);
    	animOutRight = AnimationUtils.loadAnimation(this, R.anim.view_trans_out_right);
    	animInLeft = AnimationUtils.loadAnimation(this, R.anim.view_trans_in_left);
    }
    
    private class ImageAdapter extends BaseAdapter {

    	private Context ctx;
    	int imageBackground;
    	private ArrayList<String> list;
    	public ImageAdapter(Context c, ArrayList<String> list) {
			ctx = c;
			TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
			imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
			this.list = list;
			ta.recycle();
		}

		@Override
    	public int getCount() {
    		
    		return list.size();
    	}

    	@Override
    	public Object getItem(int arg0) {
    		
    		return list.get(arg0);
    	}

    	@Override
    	public long getItemId(int arg0) {
    		
    		return arg0;
    	}

    	@Override
    	public View getView(int arg0, View arg1, ViewGroup arg2) {
    		ImageView iv = new ImageView(ctx);
    		iv.setImageResource(R.drawable.prof_pic);
    		iv.setScaleType(ImageView.ScaleType.FIT_XY);
    		iv.setLayoutParams(new Gallery.LayoutParams(150,120));
    		iv.setBackgroundResource(imageBackground);
    		return iv;
    	}

    }
    
}
